import 'dart:async';
import 'dart:collection';
import 'package:ble_helper_plugin/src/waitting_stream.dart';

// 发送处理器超时助手
class SendHandlerTimeoutHelper {
  // 静态变量保存类的唯一实例
  static final SendHandlerTimeoutHelper _instance =
      SendHandlerTimeoutHelper._internal();

  // 工厂构造函数，返回唯一实例
  factory SendHandlerTimeoutHelper() {
    return _instance;
  }

  // 私有构造函数，防止外部实例化
  SendHandlerTimeoutHelper._internal();

  // 请求队列
  final Queue<List<int>> requestQueue = Queue();

  // 响应流 Map
  Map<String, WaittingStreamController> responseStreamMap = {};

  // 定时器，用于定期检查超时
  Timer? _timeoutCheckTimer;

  // 启动超时检查
  void startTimeoutCheck({Duration? checkInterval}) {
    if (_timeoutCheckTimer != null) {
      return;
    }
    _timeoutCheckTimer = Timer.periodic(
      checkInterval ?? const Duration(milliseconds: 500),
      (timer) {
        _checkForTimeouts();
      },
    );
  }

  // 停止超时检查
  void stopTimeoutCheck() {
    _timeoutCheckTimer?.cancel();
    _timeoutCheckTimer = null;
  }

  // 检查所有 WaittingStreamController 是否超时
  void _checkForTimeouts() {
    final now = DateTime.now();
    final timedOutKeys = <String>[];

    responseStreamMap.forEach((msgId, controller) {
      if (now.difference(controller.createTime) > controller.timeout) {
        controller.streamController
            .addError(TimeoutException('Request timed out'));
        controller.streamController.close();
        timedOutKeys.add(msgId);
      }
    });

    for (var key in timedOutKeys) {
      responseStreamMap.remove(key);
    }

    if (responseStreamMap.isEmpty) {
      stopTimeoutCheck();
    }
  }
}
